package huffman;

import java.io.DataOutputStream;
import java.io.FileOutputStream;
import java.io.IOException;

public class DataOutputStreamEx {
	private DataOutputStream dos;
	private BitBuffer buffer = new BitBuffer(8);

	public void writeBit(Boolean b) throws IOException  {
		buffer.add(b);
		if(buffer.remainingCapacity() == 0) {
			byte be[] = new byte[1];
			be[0] = buffer.toByte();
			dos.write(be);
			buffer.clear();
		} 

	}
	public DataOutputStreamEx(FileOutputStream s) throws IOException {
		dos = new DataOutputStream(s);
		
	}
	public void writeByte(Byte v) throws IOException {
		for(boolean b: BitBuffer.convertToBits(v)) {
			writeBit(b);
		}
	}
	public void writeInt(Integer v) throws IOException {
		for(boolean b: BitBuffer.convertToBits(v)) {
			writeBit(b);
		}
		
//		System.out.println(v);
	}
	
	public void writeArray(boolean array[]) {
		for(boolean b: array) {
			try {
				writeBit(b);
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}
	public void close() throws IOException {
		while(buffer.remainingCapacity() != 0) {
			writeByte(buffer.toByte());
		}
//			writeByte(buffer.toByte());
	}
	
}
